package org.hbhk.hxl.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.hbhk.hxl.gateway.exception.RouteException;
import org.hbhk.hxl.gateway.redis.RedisUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

@Component
public class AuthInterceptor implements GlobalFilter, Ordered {

	@Override
	public int getOrder() {
		return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 5;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request = exchange.getRequest();
		String url = request.getURI().getPath();
		if (url.startsWith("/openapi/")) {

			String appId = request.getHeaders().getFirst("appId");
			if (StringUtils.isEmpty(appId)) {
				throw new RouteException("appId为空");
			}
			String accessToken = request.getHeaders().getFirst("accessToken");

			if (StringUtils.isEmpty(accessToken)) {
				throw new RouteException("accessToken为空");
			}

			String authToken = RedisUtil.get(String.class, appId);

			if (StringUtils.isEmpty(authToken)) {
				throw new RouteException("accessToken已过期");
			}

			if (!StringUtils.equals(accessToken, authToken)) {
				throw new RouteException("accessToken错误");
			}
		}

		return chain.filter(exchange);
	}

}
